import iButton from '@/components/carGoods/i-button.vue'
import iPreviewImage from '@/components/i-preview-image.vue'
import { mapState, mapActions } from 'vuex'

export default {
  components: { iButton, iPreviewImage },
  data() {
    return {
      // carList: [],  // 适配的车型列表
      carImgList: [], // 车品图片列表 - 上传的外观图
      typeStatus: 'add', // 当前页面的状态，add: 发布，edit: 编辑再发布

      // 表单数据，作为参数请求发布
      formData: {
        store_Id: '',
        car_Supplie_Type_Id: '',
        car_Supplie_Type_Name: '',
        type_Name: '',
        name: '',
        remark: '',
        original_Price: '',
        b_Price: '',
        c_Price: '',
        count: '',
        freight: '',
        freight_Type: 0,
        delivery_Region: 0,
        delivery_Region_Name: '',
        send_Region: 0,
        send_Region_Name: '',
        goods_Type: 2,
        operation_Account_Id: '',
        carIdList: [],
        imgList: [],
      },

      carTypeMore: false, // 控制车型列表多条显示更多按钮

      areaList: [], // 配送区域省份列表
      letterListstr: [], // 字母索引列表
      areaId: '', // 滚动区域位置标志
      deliveryAddressList: [], // 发货地列表

      shippingSettingShow: false, // 运费设置弹出框显示
      areaShow: false, // 可配送区域弹出框显示
      deliveryAddressShow: false, // 发货地弹出框显示
      shippingSettingLabel: ['默认包邮', '到付', '默认不包邮'],

      province: {
        id: 123456789,
        name: '四川省',
      }, // 省份
      city: {
        id: 2123456789,
        name: '成都市',
      }, // 城市
      submitSuccessShow: false, // 发布上架成功显示弹框

      // 是否可以点击上架出售按钮，更改按钮颜色状态
      // 返回true为可以上架，false则不能点击上架
      btnSubmitShow: false,

      previewImageShow: false, // 显示预览图片组件进行预览
      imgIndex: 0, // 预览图片的第几张 index

      // 编辑状态的表单数据详情
      editFormData: {
        added_Status: 0,
      },
      btnFlag: false, // 上架按钮请求状态控制点击
      keystatus: false, //键盘状态
      keys: '', //价格
    }
  },

  computed: {
    // 已添加设置的车型列表
    // 适配的车型列表
    ...mapState({
      carTypeList: (state) => state.carGoods.carTypeList,
      carBrandList: (state) => state.carGoods.carBrandList,
    }),

    btnSubmit: {
      get() {
        return this.btnSubmitShow
      },
      set(v) {
        this.btnSubmitShow = v
      },
    },

    // 预览的图片数组
    previewImgs: {
      set(list) {
        this.carImgList = list.map((img) => ({ img: img }))
      },
      get() {
        return this.carImgList.map((img) => img.img)
      },
    },

    // // 省，市
    // province() {
    //   return { id: 123456789, name: this.$store.state.province }
    // },

    // city() {
    //   return { id: 2123456789, name: this.$store.state.city }
    // },
  },

  watch: {
    // 监听表单数据项
    formData: {
      handler(nVal) {
        let reqs = [
          'name',
          'type_Name',
          'carIdList',
          'imgList',
          'original_Price',
          'b_Price',
          'c_Price',
          'count',
        ]
        let flag = true
        // 判断是否有空项,有空项，给flag赋值true
        for (let item of reqs) {
          if (typeof nVal[item] === 'object') {
            if (nVal[item].length === 0) {
              flag = false
              console.log('看看[][][]', item)
              break
            }
          } else {
            if (!nVal[item]) {
              flag = false
              // console.log('看看string,string', item)
              break
            }
          }
        }
        this.btnSubmit = flag
      },
      deep: true,
    },

    // 监听适配车型数组，变化时赋值给表单数据
    carTypeList(v) {
      this.formData.carIdList = v.map((item) => ({ id: item.id }))
      console.log(v)
    },

    // 监听外观图数组，变化时赋值给表单数据
    carImgList(v) {
      this.formData.imgList = v
      console.log(v)
    },
  },

  onLoad(option) {
    this.init(option)
  },

  // 监听页面返回的生命周期
  onBackPress() {
    console.log(1212121212)
    this.setCarTypeList([])

    // 处理重置vuex的车品牌列表里的checked字段为false
    this.handleCarBrandCheckedAll()
  },

  created() {
    this.formData.operation_Account_Id = uni.getStorageSync(
      'Ztc_B_USER_INFO'
    ).tid // 设置当前用户id
    this.formData.store_Id = uni.getStorageSync('userInfoDetail').store.storeId // 设置当前店铺id

    this.location(() => {
      this.getAreaList()
      this.getDeliveryAddressList()
    })
  },

  methods: {
    // vuex的添加选择的车型列表方法
    ...mapActions(['setCarTypeList', 'setCarBrandList']),

    // onLoad加载的逻辑处理
    init(option) {
      // 获取上一个页面传入的参数
      // 如果有传进来id，则是车品管理页面进来的,一定是编辑
      if (option.id) {
        this.formData.id = option.id
        this.typeStatus = 'edit'
        uni.setNavigationBarTitle({
          title: '编辑车品',
        })
        this.getCarGoodsDetail()
      } else {
        // 车品分类，从选择分类页面带过来的参数
        this.typeStatus = option.type
        const param = JSON.parse(option.param)
        this.formData.car_Supplie_Type_Name = `${param.pName}/${param.name}`
        this.formData.car_Supplie_Type_Id = param.id
      }
      uni.$on('selectedCategroy', (res) => {
        this.formData.car_Supplie_Type_Name = `${res.pName}/${res.name}`
        this.formData.car_Supplie_Type_Id = res.id
      })

      // 监听接收预览图片跳转回来的传入的新图片列表
      uni.$on('carImageS', (data) => {
        this.carImgList = data.carImageS
      })
    },

    //定位
    location(cb) {
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: (res) => {
          this.province = { id: 123456789, name: res.address.province }
          this.city = { id: 2123456789, name: res.address.city }
          cb()
        },
        fail: (err) => {
          cb()
        },
      })
    },

    // 选择车品分类
    getCategory() {
      // 如果状态为edit编辑，需要跳转到选择分类页面，
      // 状态为add，则返回上一页
      if (this.typeStatus === 'edit') {
        uni.navigateTo({
          url: '../selectTheCategory/selectTheCategory?type=edit',
        })
      } else {
        uni.navigateBack({
          delta: 1,
        })
      }
    },

    // 设置添加车型, 跳转到选择车型列表界面
    addCarType() {
      uni.navigateTo({
        url: '/pages_carGoods/selectCarType/selectCarType?Modelselection=[]',
      })
    },

    // 单独移除适配的车型
    // 实际操作vuex里的数组
    removeCarType(data, index) {
      // 已选的适配车型
      let list = this.carTypeList
      list.splice(index, 1)
      this.setCarTypeList(list)

      // 车品牌系列列表
      // 处理取消勾选，将品牌系列列表里的checked勾选改为false
      this.carBrandList.forEach((item) => {
        item.data.forEach((b) => {
          if (b.cartypeList) {
            b.cartypeList.forEach((ct) => {
              ct.carList.forEach((c) => {
                c.list.forEach((cItem) => {
                  if (cItem.id === data.id) {
                    cItem.checked = false
                  }
                })
              })
            })
          }
        })
      })
    },

    // 处理重置vuex的车品牌列表里的checked字段为false
    handleCarBrandCheckedAll() {
      let list = this.carBrandList
      list.forEach((item) => {
        item.data.forEach((b) => {
          if (b.cartypeList) {
            b.cartypeList.forEach((ct) => {
              ct.carList.forEach((c) => {
                c.list.forEach((cItem) => {
                  cItem.checked = false
                })
              })
            })
          }
        })
      })
      this.setCarBrandList(list)
    },

    // 上传车品图片
    uploadImg() {
      uni.chooseImage({
        count: 5,
        sourceType: ['album'],
        success: (res) => {
          let pms = []
          res.tempFilePaths.forEach((path) => {
            pms.push(
              this.$api.files.uploadImg({
                filePath: path,
              })
            )
          })

          Promise.all(pms)
            .then((res) => {
              // 上传图片成功后，赋值给列表
              let imgList = []
              res.forEach((item) => {
                imgList.push({
                  img: item.baseUrl + item.url,
                })
              })
              this.carImgList = [...this.carImgList, ...imgList]
            })
            .catch((err) => {
              console.log('err', err)
            })
        },
      })
    },

    // 删除所有图片
    removeImg() {
      uni.showModal({
        title: '提示',
        content: '确认删除所有图片吗？',
        success: (res) => {
          if (res.confirm) {
            this.carImgList = []
          }
        },
      })
    },

    // 预览图片多张
    previewImg(index) {
      // 跳转至图片替换/删除页面
      // uni.navigateTo({
      //   url: '/pages_carSource/vehiclePictureSelect/vehiclePictureSelect?outsideimgwg=' + encodeURIComponent(JSON.stringify(
      //     this.carImgList)) + '&&indexs=' + index + '&&Seriesid=' + 'carGoods'
      // })
      this.previewImageShow = true
      this.imgIndex = index
    },

    // 选择运费
    checkedFreight(val) {
      this.formData.freight_Type = val
      if (val !== 2) {
        this.formData.freight = ''
      }
    },

    // 获取区域列表
    async getAreaList() {
      const res = await this.$api.jsonData.regionalProvinceGroup()
      this.areaList = res.data.list

      this.handleAddress(this.areaList, this.province, 'province')
    },

    // 获取发货地列表
    async getDeliveryAddressList() {
      const res = await this.$api.jsonData.regionalCityGroup()
      this.deliveryAddressList = res.data.list
      this.letterListstr = res.data.liststr

      this.handleAddress(this.deliveryAddressList, this.city, 'city')
    },

    // 需要获取当前定位的省份，然后从省份列表查找出定位省份的id
    // 如当前定位为：四川省，则匹配四川省的id
    // 然后把当前省份作为默认值显示在页面上的 可配送区域 选项中
    // 发货地选项处理也是如此
    handleAddress(list, address, type) {
      let keyName = {
        province: 'delivery_Region',
        city: 'send_Region',
      }
      // 将二维数组处理成平面的一维数组
      let oneDlist = list.map((e) => e.data).reduce((a, b) => a.concat(b))
      let findObj = oneDlist.find((item) => item.name === address.name)
      console.warn(findObj)
      this.formData[`${keyName[type]}_Name`] = findObj.name
      this.formData[keyName[type]] = findObj.id

      address.id = findObj.id // 给定位的省份和城市赋值id
    },

    // 选择可配送区域
    checkedArea(area) {
      this.formData.delivery_Region_Name = area.name
      this.formData.delivery_Region = area.id
      this.areaShow = false
    },

    // 选择发货地
    checkedAddress(address) {
      this.formData.send_Region_Name = address.name
      this.formData.send_Region = address.id
      this.deliveryAddressShow = false
    },

    // 点击运费设置完成
    shipSettingOk() {
      // 如果选择了默认不包邮，就需要填写邮费
      if (this.formData.freight_Type === 2) {
        if (!parseFloat(this.formData.freight)) {
          uni.showToast({
            title: '运费不能为空或0',
            icon: 'none',
          })
        } else {
          this.shippingSettingShow = false
        }
      } else {
        this.shippingSettingShow = false
      }
    },

    // 判断表单是否有未填项
    hasEmpty() {
      let flag = false
      let tips = new Map([
        ['store_Id', '店铺不能为空'],
        ['car_Supplie_Type_Id', '车品分类不能为空'],
        ['car_Supplie_Type_Name', '车品分类不能为空'],
        ['name', '品牌名称不能为空'],
        ['type_Name', '型号名称不能为空'],
        ['carIdList', '请选择适配车型'],
        ['imgList', '请上传车品外观图'],
        ['original_Price', '商品原价不能为空'],
        ['b_Price', '商家端销售价格不能为空'],
        ['c_Price', '消费端销售价格不能为空'],
        ['count', '库存不能为空'],
        // ['freight', '运费不能为空或0'],
      ])
      if (this.formData.freight_Type === 2) {
        tips.set('freight', '运费不能为空或0')
      }
      // 遍历必填项，必填项没有值时，弹出对应提示语
      for (let key of tips.keys()) {
        let val = this.formData[key]
        // 如果为object，说明是车型id和车品外观图的数组
        if (typeof val === 'object') {
          if (val.length === 0) {
            uni.showToast({
              title: tips.get(key),
              icon: 'none',
            })
            flag = true
            break
          }
        } else {
          console.log(key, val)
          if (!val) {
            uni.showToast({
              title: tips.get(key),
              icon: 'none',
            })
            flag = true
            break
          }
        }
      }
      return flag
    },

    // 提交 - 上架出售
    async submit() {
      if (this.btnFlag) return
      this.btnFlag = true
      // 上架出售前检查是否有空项未填
      if (this.hasEmpty()) return false

      // 将字符串的数字转成Number类型数字
      this.formData.original_Price = parseFloat(this.formData.original_Price)
      this.formData.b_Price = parseFloat(this.formData.b_Price) || 0
      this.formData.c_Price = parseFloat(this.formData.c_Price) || 0
      this.formData.count = parseFloat(this.formData.count)
      this.formData.freight = parseFloat(this.formData.freight) || 0
      this.formData.send_Region = parseFloat(this.formData.send_Region)
      // 如果适配车型的id有123456789的，则是所有车型，传[]就可以，
      let isCarAll = this.formData.carIdList.find(
        (item) => item.id === 123456789
      )
      this.formData.carIdList = isCarAll ? [] : this.formData.carIdList
      console.log(this.formData)

      try {
        // 发布新增
        if (this.typeStatus === 'add') {
          uni.showLoading({
            title: '发布中',
          })
          await this.$api.carGoods.AddGoodsSupplie(this.formData)
          this.submitSuccessShow = true
          this.btnFlag = false
        } else {
          // 编辑车品
          uni.showLoading({
            title: '正在保存',
          })
          await this.$api.carGoods.UpdateGoodsSupplie(this.formData)
          uni.showToast({
            title: '保存成功',
          })
          let t = setTimeout(() => {
            clearTimeout(t)
            uni.redirectTo({
              url: '/pages_carGoods/carGoodsManage/carGoodsManage',
            })
          }, 1000)
        }
        uni.hideLoading()
      } catch (err) {
        //
        uni.hideLoading()
      }
    },

    // 上架成功后，点我知道了
    goPage() {
      this.submitSuccessShow = false
      this.setCarTypeList([]) // 清空已选车型
      this.handleCarBrandCheckedAll()
      uni.redirectTo({
        url: '/pages_carGoods/carGoodsManage/carGoodsManage',
      })
    },

    // 当前发布也为编辑状态时,需要获取车品详情信息
    async getCarGoodsDetail() {
      // 请求车品详情信息
      try {
        uni.showLoading()
        const res = await this.$api.carGoods.GetCarSupplieDetails({
          id: this.formData.id,
        })
        this.editFormData = res.data
        console.log('车品详情', res.data)
        // 遍历接口入参对象进行需要的赋值
        Object.keys(this.formData).forEach((key) => {
          this.formData[key] = res.data[key]
        })
        this.formData.carIdList = res.data.carlist.map((c) => c.id) // 赋值适配车型id
        // 处理适配车型显示的列表
        this.setCarTypeList(
          res.data.carlist.length !== 0
            ? res.data.carlist
            : [
                {
                  id: 123456789,
                  name: '适用所有车型',
                },
              ]
        )

        this.formData.imgList = res.data.facade_Picture || []
        this.carImgList = res.data.facade_Picture || [] // 车品图片
        this.formData.operation_Account_Id = uni.getStorageSync(
          'Ztc_B_USER_INFO'
        ).tid // 设置当前用户id
        // 处理适配车型数组
        if (this.carBrandList.length === 0) {
          this.setCarBrandList()
        } else {
          // 处理取消勾选，将品牌系列列表里的checked勾选改为false
          let list = this.carBrandList
          list.forEach((item) => {
            item.BrandList.forEach((b) => {
              b.CartypeList.forEach((ct) => {
                ct.CarList.forEach((c) => {
                  c.list.forEach((cItem) => {
                    if (cItem.Id === data.id) {
                      cItem.checked = false
                    }
                  })
                })
              })
            })
          })
          this.setCarBrandList(list)
        }
      } catch (err) {
        //
      }
      uni.hideLoading()
    },

    // 删除、上架、下架操作
    updateCarGoods(type, tips) {
      uni.showModal({
        title: tips,
        content: `确认${tips}该车品吗？`,
        confirmColor: '#FBB000',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading()
            try {
              await this.$api.carGoods.UpdateCarSupplie({
                type,
                goodsid: [this.formData.id],
              })
              uni.showToast({
                title: tips + '成功',
              })
              let t = setTimeout(() => {
                clearTimeout(t)
                uni.redirectTo({
                  url: '/pages_carGoods/carGoodsManage/carGoodsManage',
                })
              }, 1000)
            } catch (err) {}
          }
        },
      })
    },

    inputChange(e) {
      // console.log('input输入中', e, e.detail.value)
      this.formData.original_Price = 1
    },
    // 退格键被点击
    backspace() {
      // 删除value的最后一个字符
      if (this.formData[this.keys].length) {
        this.formData[this.keys] = this.formData[this.keys].substr(
          0,
          this.formData[this.keys].length - 1
        )
      }

      console.log(this.formData[this.keys])
    },
    // 获取键盘输入值
    getmyquotation(e) {
      // console.log('获取报价值',e)
			if(this.keys!=='count'){
			  let reg = /^(\d+)(.\d{0,1})?$/
			  // console.log(reg.test(this.formData[this.keys]))
				if(this.formData[this.keys].length>3){
					if(!reg.test(this.formData[this.keys])){
					  uni.showToast({
						  title: '请保留两位小数',
						  duration: 2000,
						  icon: 'none'
					  })
					  // this.formData[this.keys]=''
					}else{
						 this.formData[this.keys] = this.formData[this.keys] + e + ''
					}
				}else{
						 this.formData[this.keys] = this.formData[this.keys] + e + ''
					}
		
			}
     
    },
    setType(type) {
      this.keystatus = !this.keystatus
      this.keys = type
    },

    blurMoney() {
		  if(this.keys!=='count'){
        let reg = /^(\d+)(.\d{0,2})?$/
        // console.log(reg.test(this.formData[this.keys]))
        if(!reg.test(this.formData[this.keys])){
          uni.showToast({
					  title: '请保留两位小数',
					  duration: 2000,
					  icon: 'none'
          })
          this.formData[this.keys]=''
        }
		  }
    },
  },
}
